﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Jumpton.SFA.Server.BusinessRule.MasterData;
using Jumpton.SFA.Server.Entity;
using Jumpton.SFA.Server.BusinessRule;
using Jumpton.SFA.Server.BusinessRule.System;
using Jumpton.SFA.Server.BusinessRule.InStoreDataMeasures;
using Jumpton.Persistent;
public partial class Customer_Maintain : PageBase
{
    #region 定义变量
    private decimal id = 0;
    private const string CUSTOMER_ID = "id";
    private const string RETURN_PAGE = "Customer_List.aspx";
    private const string ADD_CONTACT = "Contact_Person_Maintain.aspx?customerID=";
    private const string ADD_TIME = "ExecuteTime_Maintain.aspx?customerID=";

    private const string ADD_DISTRIBUTION = "Distribution_Maintain.aspx?customerID=";
    private OrgainzationManager orgManager = new OrgainzationManager();
    private RegionManager regionManager = new RegionManager();
    private string provinceID;
    private string cityID;
    private string areaID;
    private static string COUNTRY_CODE = "CN";
    private string contactDistrict;//contactInfo表中的区域编号
    private Boolean ReadOnly;

    #endregion

    /// <summary>
    /// Handles the Load event of the Page control.e
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    protected void Page_Load(object sender, EventArgs e)
    {
        decimal.TryParse(Request.QueryString[CUSTOMER_ID], out id);
        string from = Request.QueryString["From"];
        ReadOnly = Request.QueryString.ToString().ToUpper().IndexOf("READONLY") > -1;
        if (!IsPostBack)
        {
            ViewState["from"] = from;
            DataBind();
            //绑定省市区
            Area();

            if (id > 0)
            {
                ViewState["customerId"] = id.ToString();

                //int count = new CustomerManager().GetStorePhotoCount(id);

            }
            InitForm();
            this.FillForm(sender, e);
            if (ReadOnly)
            {
                btnSave.Visible = false;
            }

        }

    }





    private void Area()
    {
        ///通过最小一级获取省市区
        try
        {

            var contact = new ContactManager().Load(id);
            if (contact == null)
            {
                BindArea();
                return;
            }
            contactDistrict = contact.DISTRICT;//获取区域号
            int level = 0;
            String Code = "";
            if (!string.IsNullOrEmpty(contactDistrict))
            {
                level = 4;
                Code = contactDistrict;
            }
            else if (!string.IsNullOrEmpty(contact.CITY))
            {
                level = 3;
                Code = contact.CITY;
            }
            else if (!string.IsNullOrEmpty(contact.STATE))
            {
                level = 2;
                Code = contact.STATE;
            }
            else if (!string.IsNullOrEmpty(contact.COUNTRYCODE))
            {
                level = 1;
                Code = contact.COUNTRYCODE;
            }
            else
            {
                level = 0;

            }
            var dt = new RegionManager().GetRegionData(MyStateManager.DomainID, level, Code);
            var region = dt[0] as REGIONS;
            if (level == 4)
            {
                provinceID = region.STATECODE;
                cityID = region.CITYCODE;
                areaID = region.DISTRICTCODE;
                COUNTRY_CODE = region.COUNTRYCODE;
            }
            else if (level == 3)
            {
                provinceID = region.STATECODE;
                cityID = region.CITYCODE;
                COUNTRY_CODE = region.COUNTRYCODE;
            }
            else if (level == 2)
            {
                provinceID = region.STATECODE;
                COUNTRY_CODE = region.COUNTRYCODE;
            }
            else
            {
                COUNTRY_CODE = region.COUNTRYCODE;
            }
            BindArea();
        }
        catch
        {

        }

    }

    private void BindArea()
    {
        //省
        ddlProvince.DataTextField = "STATE_Name";
        ddlProvince.DataValueField = "STATE_CODE";
        ddlProvince.DataSource = regionManager.GetRegionDistinctData(MyStateManager.DomainID, 1, COUNTRY_CODE);
        ddlProvince.DataBind();
        ddlProvince.Items.Insert(0, new ListItem(Resources.language.ddl_Select, ""));
        ddlProvince.SelectedValue = provinceID;

        //市
        if (!string.IsNullOrEmpty(provinceID))
        {
            ddlCity.DataTextField = "CITY_NAME";
            ddlCity.DataValueField = "CITY_CODE";
            ddlCity.DataSource = regionManager.GetRegionDistinctData(MyStateManager.DomainID, 2, provinceID);
            ddlCity.DataBind();
            ddlCity.Items.Insert(0, new ListItem(Resources.language.ddl_Select, ""));
            ddlCity.SelectedValue = cityID;
        }

        //区
        if (!string.IsNullOrEmpty(cityID))
        {
            ddlArea.DataTextField = "DISTRICT_NAME";
            ddlArea.DataValueField = "DISTRICT_CODE";
            ddlArea.DataSource = regionManager.GetRegionDistinctData(MyStateManager.DomainID, 3, cityID);
            ddlArea.DataBind();
            ddlArea.Items.Insert(0, new ListItem(Resources.language.ddl_Select, ""));
            ddlArea.SelectedValue = areaID;
        }
    }

    /// <summary>
    /// 选择省
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void ddlProvince_SelectedIndexChanged(object sender, EventArgs e)
    {
        provinceID = string.Empty;
        cityID = string.Empty;
        areaID = string.Empty;
        this.ddlCity.Items.Clear();
        this.ddlArea.Items.Clear();

        provinceID = this.ddlProvince.SelectedValue;

        if (!string.IsNullOrEmpty(provinceID))
        {
            ddlCity.DataTextField = "CITY_NAME";
            ddlCity.DataValueField = "CITY_CODE";
            ddlCity.DataSource = regionManager.GetRegionDistinctData(MyStateManager.DomainID, 2, provinceID);
            ddlCity.DataBind();
            ddlCity.Items.Insert(0, new ListItem(Resources.language.ddl_Select, ""));
            ddlCity.SelectedValue = cityID;
        }
    }

    /// <summary>
    /// 选择市
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void ddlCity_SelectedIndexChanged(object sender, EventArgs e)
    {
        this.ddlArea.Items.Clear();

        cityID = this.ddlCity.SelectedValue;

        //区
        if (!string.IsNullOrEmpty(cityID))
        {
            ddlArea.DataTextField = "DISTRICT_NAME";
            ddlArea.DataValueField = "DISTRICT_CODE";
            ddlArea.DataSource = regionManager.GetRegionDistinctData(MyStateManager.DomainID, 3, cityID);
            ddlArea.DataBind();
            ddlArea.Items.Insert(0, new ListItem(Resources.language.ddl_Select, ""));
            ddlArea.SelectedValue = areaID;
        }
    }


    #region 下拉框数据绑定
    /// <summary>
    /// Inits the form.
    /// </summary>
    private void InitForm()
    {

        DictionaryItemsManager dim = new DictionaryItemsManager();

        //销售渠道
        ddlChannel.DataTextField = "Name";
        ddlChannel.DataValueField = "DictionaryItemId";
        ddlChannel.DataSource = dim.GetItemList(DictionaryEnum.CustomerChannel, this.MyStateManager.DomainID);
        ddlChannel.DataBind();
        ddlChannel.Items.Insert(0, new ListItem(Resources.language.ddl_Select, ""));



        //客户类型
        drpCustomerType.DataTextField = "Name";
        drpCustomerType.DataValueField = "DictionaryItemId";
        drpCustomerType.DataSource = dim.GetItemList(DictionaryEnum.CustomerClass, this.MyStateManager.DomainID);
        drpCustomerType.DataBind();
        drpCustomerType.Items.Insert(0, new ListItem(Resources.language.ddl_Select, ""));

        //指标组
        //ddlMeasures.DataSource = new MeasureProfilesManager().GetMeasuresProfilesDistributionTable(MyStateManager.DomainID, "1");
        //ddlMeasures.DataTextField = "NAME";
        //ddlMeasures.DataValueField = "ProfilesID";
        //ddlMeasures.DataBind();
        //ddlMeasures.Items.Insert(0, new ListItem(Resources.language.ddl_Select, ""));

        ddlMeasures.DataSource = new MeasuresGroupManager().GetMeasuresGroupTable(MyStateManager.DomainID, "1");
        ddlMeasures.DataTextField = "NAME";
        ddlMeasures.DataValueField = "ID";
        ddlMeasures.DataBind();
        ddlMeasures.Items.Insert(0, new ListItem(Resources.language.ddl_Select, ""));

        //客户等级
        ddlCustomerLevel.DataSource = dim.GetItemList(DictionaryEnum.Store_Level, MyStateManager.DomainID);
        ddlCustomerLevel.DataTextField = "NAME";
        ddlCustomerLevel.DataValueField = "DictionaryItemId";
        ddlCustomerLevel.DataBind();
        ddlCustomerLevel.Items.Insert(0, new ListItem(Resources.language.ddl_Select, ""));
    }
    #endregion


    /// <summary>
    /// Fills the form.
    /// </summary>
    private void FillForm(object sender, EventArgs e)
    {

        if (id > 0)
        {
            CUSTOMERS customer = new CustomerManager().Load(id);
            if (customer != null)
            {
                
                txtName.Text = customer.NAME;
                chxValid.Checked = customer.ACTIVE;
                txtHidOrg.Value = customer.ORGID.ToString();
                if (customer.ORGID != null)
                {
                    ORGANIZATION org = orgManager.Load(customer.ORGID);
                    txtOrg.Text = org.NAME;
                    string addres = org.ORGLEVEL.ToString();
                    setTxt_OrgText(addres);
                }
                //获取经度，纬度,以后需要修改，店面位置，门店面积用的也是IDENTITY1,IDENTITY2字段
                txtLongitude.Text = customer.IDENTITY1.ToString();
                txtlatitude.Text = customer.IDENTITY2.ToString();

                txtCustomerCode.Text = customer.CODE;


                try
                {
                    foreach (ListItem item in ddlMeasures.Items)
                    {
                        if (item.Value == customer.MEASUREPROFILEID.ToString())
                        {
                            item.Selected = true;
                            break;
                        }
                    }


                }
                catch { }

                ddlChannel.SelectedValue = customer.LOCALLEVEL1CODE;
                ddlCustomerLevel.SelectedValue = customer.LOCALLEVEL2CODE;

                drpCustomerType.SelectedValue = customer.CUSTCLASSCODE;
            }
            CONTACT_INFO contact = new ContactManager().Load(id);
            if (contact != null)
            {
                txtAddress.Text = contact.ADDRESSLINE;
                txtPhone.Text = contact.TELEPHONE;
                //txtCity.Text = contact.CITY;
                txtZipCode.Text = contact.POSTALCODE;
                txtContact.Text = contact.SLOGCODE;

                //ctlTable.DataSource = contact;
                //ctlTable.DataBind();
            }
        }
    }


    private void setTxt_OrgText(string addres)
    {
        txt_OrgAddress.Text = "中国";
        if (addres != "CN" && addres !="0")
        {
            RegionManager rm = new RegionManager();
            string sqlwhere = "";
            string selectCol = "";
            if (addres.Length == 2)
            {
                sqlwhere = " AND STATE_CODE=" + addres;
                selectCol = "STATE_NAME";
            }
            else if (addres.Length == 4)
            {
                sqlwhere = " AND CITY_CODE=" + addres;
                selectCol = " STATE_NAME,CITY_NAME ";
            }
            else if (addres.Length == 6)
            {
                sqlwhere = " AND DISTRICT_CODE=" + addres;
                selectCol = " STATE_NAME,CITY_NAME,DISTRICT_NAME ";
            }
            DataTable dt = rm.GetRegionTable(sqlwhere, MyStateManager.DomainID, selectCol);
            for (int i = 0, colCount = dt.Columns.Count; i < colCount; i++)
            {
                if (dt.Rows.Count > 0)
                {
                    txt_OrgAddress.Text += dt.Rows[0][i].ToString();
                }
            }
        }
        hd_org.Value = addres;
    }

    ///// <summary>
    ///// Handles the Click event of the btnNewTime control.
    ///// </summary>
    ///// <param name="sender">The source of the event.</param>
    ///// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    protected void btnNewTime_Click(object sender, EventArgs e)
    {
        //try
        //{
        //    int newID = this.SaveData();
        //    Response.Redirect(ADD_TIME + newID.ToString());
        //}
        //catch (Exception ex)
        //{
        //    ShowMessage(ex.Message);
        //}

    }
    /// <summary>
    /// Handles the Click event of the btnSave control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    protected void btnSave_Click(object sender, EventArgs e)
    {
        try
        {
            if (ddlCheck()) return;
            SaveData(true);

            ShowMessage("保存成功", RETURN_PAGE + "?" + Request.QueryString);

        }
        catch (Exception ex)
        {
            ShowMessage(ex.Message);
        }

    }
    protected void btnCancel_Click(object sender, EventArgs e)
    {

        if (null != ViewState["from"])
        {
            Response.Redirect("CustomerMapList.aspx");
        }
        else
            Response.Redirect(RETURN_PAGE + "?" + Request.QueryString);
    }
    private decimal SaveData(bool IsMsgOrgError)
    {
        string LogContent = "";
        CUSTOMERS pendingCustomer = null;
        CONTACT_INFO pendingCustomerInfo = null;
        CustomerManager manager = new CustomerManager();
        if (id > 0)  //修改客户资料
        {

            CUSTOMERS customer = new CustomerManager().Load(id);
            pendingCustomer = manager.Load(id);
            if (pendingCustomer == null)
            {
                pendingCustomer = new CUSTOMERS();
                pendingCustomer.ID = id;
            }
            pendingCustomer.LOCALLEVEL2CODE = customer.LOCALLEVEL2CODE;
            pendingCustomer.ADDITIONALINFO = customer.ADDITIONALINFO;
            pendingCustomer.BANNERCODE = customer.BANNERCODE;


            try
            {
                pendingCustomer.CHAINCODE = customer.CHAINCODE;
                pendingCustomer.CUSTCLASSCODE = customer.CUSTCLASSCODE;
                pendingCustomer.DEFAULTSHIPTOCODE = customer.DEFAULTSHIPTOCODE;
                pendingCustomer.GEOLEVELCODE = customer.GEOLEVELCODE;
                pendingCustomer.NAME2 = customer.NAME2;

            }
            catch (Exception ex)
            {
                ShowMessage(ex.Message);
            }


            pendingCustomer.CODE = txtCustomerCode.Text;

            pendingCustomerInfo = new ContactManager().Load(id);
            if (pendingCustomerInfo == null)
            {
                pendingCustomerInfo = new CONTACT_INFO();
                pendingCustomerInfo.CUSTOMERID = id;
            }
            CONTACT_INFO info = new ContactManager().Load(id);
            if (info != null)
            {
                pendingCustomerInfo.ADDRESSLINE2 = info.ADDRESSLINE2;
                pendingCustomerInfo.COUNTRYCODE = info.COUNTRYCODE;
                pendingCustomerInfo.EMAIL = info.EMAIL;
                pendingCustomerInfo.FAX = info.FAX;

            }

        }
        else
        {
            pendingCustomerInfo = new CONTACT_INFO();
            pendingCustomer = new CUSTOMERS();
            pendingCustomer.ID = decimal.Parse(MyStateManager.PersonID + DateTime.Now.ToString("yyyyMMddHHmmss") + new Random().Next(1000, 9999));
            pendingCustomerInfo.CUSTOMERID = pendingCustomer.ID;

            pendingCustomer.CODE = txtCustomerCode.Text;
        }
        pendingCustomer.IDENTITY1 = String.IsNullOrEmpty(txtLongitude.Text.Trim()) ? 0 : double.Parse(txtLongitude.Text.Trim());//经度
        pendingCustomer.IDENTITY2 = String.IsNullOrEmpty(txtlatitude.Text.Trim()) ? 0 : double.Parse(txtlatitude.Text.Trim());//维度
        pendingCustomer.STATUS = "0";
        pendingCustomer.NAME = txtName.Text;
        pendingCustomer.LOCALLEVEL1CODE = ddlChannel.SelectedValue;
        pendingCustomer.LOCALLEVEL2CODE = ddlCustomerLevel.SelectedValue;
        pendingCustomer.ORGID = int.Parse(txtHidOrg.Value.Replace("'", ""));
        //pendingCustomer.CUSTOMERPRODUCTLISTID = 0;
        pendingCustomer.PARENTCODE = "default";
        pendingCustomer.ACTIVE = this.chxValid.Checked;
        pendingCustomer.DEFAULTUOMCODE = "PC";
        pendingCustomer.DOMAINID = this.MyStateManager.DomainID;
        pendingCustomer.LAST_UPDATE = this.MyStateManager.UserID.ToString();

        pendingCustomer.CREATE_TIME = decimal.Parse(DateTime.Now.ToString("yyyyMMddHHmmss"));

        pendingCustomer.LAST_UPDATE_TIME = decimal.Parse(DateTime.Now.ToString("yyyyMMddHHmmss"));
        pendingCustomer.MEASUREPROFILEID = decimal.Parse(ddlMeasures.SelectedValue);
        if (drpCustomerType.SelectedIndex > 0)
            pendingCustomer.CUSTCLASSCODE = drpCustomerType.SelectedValue;

        manager.Save(pendingCustomer);
        pendingCustomerInfo.COUNTRYCODE = COUNTRY_CODE;
        if (!string.IsNullOrEmpty(this.ddlArea.SelectedValue))
        {
            pendingCustomerInfo.DISTRICT = this.ddlArea.SelectedValue;
        }
        if (!string.IsNullOrEmpty(this.ddlCity.SelectedValue))
        {
            pendingCustomerInfo.CITY = this.ddlCity.SelectedValue;
        }
        if (!string.IsNullOrEmpty(this.ddlProvince.SelectedValue))
        {
            pendingCustomerInfo.STATE = this.ddlProvince.SelectedValue;
        }

        pendingCustomerInfo.ADDRESSLINE = txtAddress.Text;
        pendingCustomerInfo.TELEPHONE = txtPhone.Text;
        pendingCustomerInfo.LAST_UPDATE_TIME = decimal.Parse(BusinessLogic.GetDateTimeString(DateTime.Now));
        pendingCustomerInfo.POSTALCODE = txtZipCode.Text;
        pendingCustomerInfo.SLOGCODE = txtContact.Text;
        pendingCustomerInfo.LAST_UPDATE = this.MyStateManager.UserID.ToString();
        pendingCustomerInfo.ACTIVE = chxValid.Checked;

        LogContent += "新增或修改客户信息为：";
        LogContent += " 门店名称：" + pendingCustomer.NAME + "，";
        LogContent += " 地址：" + pendingCustomerInfo.ADDRESSLINE + "，";
        LogContent += " 联系电话：" + pendingCustomerInfo.TELEPHONE + "，";
        LogContent += " 联系人：" + pendingCustomerInfo.SLOGCODE + "，";
        LogContent += " 客户类型：" + drpCustomerType.SelectedItem.Text + "，";
        LogContent += " 邮政编码：" + pendingCustomerInfo.POSTALCODE + "，";
        LogContent += " 销售渠道：" + ddlChannel.SelectedItem.Text + "，";
        LogContent += " 指标组：" + ddlMeasures.SelectedItem.Text + "，";
        LogContent += " 备注：" + txtRemark.Text + "，";
        LogContent += " 经度：" + txtLongitude.Text + "，";
        LogContent += " 纬度：" + txtlatitude.Text + "，";

        if (ddlProvince.SelectedItem != null)
            LogContent += "省：" + ddlProvince.SelectedItem.Text + "，";
        if (ddlCity.SelectedItem != null)
            LogContent += "市：" + ddlCity.SelectedItem.Text + "，";
        if (ddlArea.SelectedItem != null)
            LogContent += "区：" + ddlArea.SelectedItem.Text;
        //ctlTable.SaveValue(pendingCustomerInfo);
        try
        {
            new ContactManager().Save(pendingCustomerInfo);

            Jumpton.SFA.Server.BusinessRule.System.EventManager.CreateNewEvent(
              Jumpton.SFA.Server.BusinessRule.System.LogType.Info_Change, this.MyStateManager.Name,
              this.MyStateManager.UserID, LogContent);
        }
        catch (Exception ex)
        {

            Jumpton.SFA.Server.BusinessRule.System.EventManager.CreateNewEvent(
              Jumpton.SFA.Server.BusinessRule.System.LogType.GENERAL_EXCEPTION, this.MyStateManager.Name,
              this.MyStateManager.UserID, "新增客户 - 异常:" + ex.Message);
        }
        return pendingCustomer.ID;
    }

    protected void btnNewDis_Click(object sender, EventArgs e)
    {
        try
        {
            decimal newID = this.SaveData(false);
            Response.Redirect(ADD_DISTRIBUTION + newID.ToString());
        }
        catch (Exception ex)
        {
            ShowMessage(ex.Message);
        }
    }
    private bool ddlCheck()
    {
        if (ddlArea.SelectedValue == "")
        {
            ShowMessage("行政架构必须选择县区");
            return true;
        }
        if (ddlProvince.SelectedValue == "" && ddlCity.SelectedValue == "" && ddlArea.SelectedValue == "")
        {
            ShowMessage("请选择行政架构！");
            return true;
        }
        if (hd_org.Value!="0"&&hd_org.Value!="CN")
        {
            if (hd_org.Value == ddlProvince.SelectedValue || ddlCity.SelectedValue == hd_org.Value || ddlArea.SelectedValue == hd_org.Value)
            {
                return false;
            }
            else
            {
                ShowMessage("所选行政架构与组织架构所在行政架构不同");
                return true;
            }
        }
        return false;
    }

    protected void txtOrg_TextChanged(object sender, EventArgs e)
    {
        string orgtext = txtOrg.Text;
        ORGANIZATION organization = new ORGANIZATION();
        organization.NAME = orgtext;
        organization = new OrgainzationManager().Load(orgtext, MyStateManager.DomainID);
        string level = organization.ORGLEVEL.ToString();
        setTxt_OrgText(level);
        ddlArea.Items.Clear();
        ddlCity.Items.Clear();

        if (level.Length >= 2)
        {
            int l;
            if (int.TryParse(level.Substring(0, 2), out l))
            {
                ddlProvince.SelectedValue = level.Substring(0, 2);
                this.RegionOnSelectedIndexChanged(ddlProvince, EventArgs.Empty);
            }
        }
        if (level.Length >= 4)
        {
            ddlCity.SelectedValue = level.Substring(0, 4);
            //var dt = ddlCity.DataSource;
            this.RegionOnSelectedIndexChanged(ddlCity, EventArgs.Empty);
        }
        if (level.Length >= 6)
        {
            ddlArea.SelectedValue = level.Substring(0, 6);
            this.RegionOnSelectedIndexChanged(ddlArea, EventArgs.Empty);
        }
    }



    protected void RegionOnSelectedIndexChanged(object sender, EventArgs e)
    {
        if (sender == ddlProvince)
        {
            ddlCity.DataSource = new RegionManager().GetRegionDistinctData(MyStateManager.DomainID, 2, ddlProvince.SelectedValue);
            ddlCity.DataValueField = "CITY_CODE";
            ddlCity.DataTextField = "CITY_NAME";
            ddlCity.DataBind();
            ddlCity.Items.Insert(0, new ListItem("全部", null));
            //RegionOnSelectedIndexChanged(ddlCity, e);
        }
        else if (sender == ddlCity)
        {
            ddlArea.DataSource = new RegionManager().GetRegionDistinctData(MyStateManager.DomainID, 3, ddlCity.SelectedValue);
            ddlArea.DataValueField = "DISTRICT_CODE";
            ddlArea.DataTextField = "DISTRICT_NAME";
            ddlArea.DataBind();
            ddlArea.Items.Insert(0, new ListItem("全部", null));
        }
    }
}
